﻿using CommonLib.Util;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace CommonLib.Info;

public static class SqlStringList
{
    private static readonly Dictionary<string, string> Collect = new();

    private static int idx = 1;

    public static List<string> Init(List<string> list)
    {
        Collect.Clear();
        var li = new List<string>();
        for (int i = 0; i < list.Count; i++)
        {
            var item = list[i];
            if (item.StartsWith("--"))
            {
                li.Add(item);
                continue;
            }
            var mats = Regex.Matches(item, "('.*?')");
            if (mats.Count > 0)
            {
                var row = item;
                foreach (Match mat in mats.Cast<Match>())
                {
                    Collect.Add($"STRLIST_{idx}", mat.Result("$1"));
                    row = row.ReplaceFirst(mat.Value, $"STRLIST_{idx}");
                    idx++;
                }
                li.Add(row);
            }
            else li.Add(item);
        }
        return li;
    }

    public static string GetItem(string str)
    {
        var mats = Regex.Matches(str, "STRLIST_\\d+");
        if (mats.Count > 0)
        {
            foreach (Match mat in mats.Cast<Match>())
            {
                str = str.Replace(mat.Value, Collect[mat.Value]);
            }
        }
        return str;
    }
}
